package com.lifp.controller;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfWidgetAnnotation;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * 图片填充
 * @author lifp
 * @date 2023/04/24
 */
@Api(tags = "图片填充")
@RestController
@RequestMapping("/image/fill")
public class ImageFillController {



    @SneakyThrows
    @ApiOperation("预览")
    @GetMapping(value = "preview", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<byte[]> fillImagePreview(){
        final String src = "src/main/resources/adv/contract.pdf";
        final String imagePath = "src/main/resources/adv/adv.png";

        PdfReader pdfReader = new PdfReader(src);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfWriter pdfWriter = new PdfWriter(outputStream);

        PdfDocument pdfDocument = new PdfDocument(pdfReader, pdfWriter);

        //获取PDF表单域
        PdfAcroForm acroForm = PdfAcroForm.getAcroForm(pdfDocument, false);
        //获取图片具体表单
        PdfFormField advatarFormField = acroForm.getField("advatar");

        //获取控件对象
        List<PdfWidgetAnnotation> widgets = advatarFormField.getWidgets();
        PdfWidgetAnnotation widget = widgets.get(0);

        //获取左下角坐标
        float x1 = widget.getRectangle().getAsNumber(0).floatValue();
        float y1 = widget.getRectangle().getAsNumber(1).floatValue();

        //获取右上角坐标
        float x2 = widget.getRectangle().getAsNumber(2).floatValue();
        float y2 = widget.getRectangle().getAsNumber(3).floatValue();

         //域宽、高
        float fieldWidth = x2 - x1;
        float fieldHeight = y2 - y1;

        //创建图片对象
        Image image = new Image(ImageDataFactory.create(imagePath));
        //图片自适应缩放
        image.scaleToFit(fieldWidth,fieldHeight);
        //获取图片缩放后的宽、高
        float scaledWidth = image.getImageScaledWidth();
        float scaledHeight = image.getImageScaledHeight();

        //计算图片居中位置
        //x = 域x坐标 + （图片宽度/2）-（自适应后图片宽度/2）
        //y = 域y坐标 + （图片高度/2）-（自适应后图片高度/2）

        float centerX = x1 + fieldWidth / 2 - scaledWidth / 2;
        float centerY = y1 + fieldHeight / 2 - scaledHeight / 2;
        //设置图片位置
        image.setFixedPosition(centerX,centerY);

        //创建Document 并将图片添加到其中
        Document document = new Document(pdfDocument);
        document.add(image);

        //清除表单域
        acroForm.flattenFields();
        document.close();

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "inline; filename=hello.pdf");
        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_PDF)
                .body(outputStream.toByteArray());
    }
}